<?php

declare (strict_types = 1);

namespace own\middleware;

use app\service\admin\system\LoggerService;
use app\service\admin\system\RoleService;
use own\enum\CacheKey;
use own\helps\RespCode;
use own\helps\JwtAuth;
use own\interface\OwnMiddlewareInterface;
use think\facade\Cache;
use think\facade\Config;
use think\Response;

class AdminMiddleware extends OwnMiddlewareInterface
{
    /**
     * 处理请求信息
     * @param Request $request
     * @param string $token
     * @param Closure  $next
     * @return Response
     */
    public function handleRequest($request, $token, $next)
    {
        $request->port = 1;//端口：1管理端api 2客户端api
        if (!$token) {
            tips('请先登录', RespCode::NOT_LOGIN);
        }
        $user = make(JwtAuth::class)->verify($token);
        if (!$user) {
            tips('请重新登录', RespCode::NOT_LOGIN);
        }
        $cacheToken = Cache::store('redis')->hget(CacheKey::OWN_USIGN, 'u' . $user->uid);
        if (!$cacheToken) {
            tips('请重新登录', RespCode::NOT_LOGIN);
        }
        if (Config::get('jwt.admin_login') == 'sso' && $cacheToken != $token) {
            tips('你已被登出，请重新登录', RespCode::NOT_LOGIN);
        }
        $request->uid = (int) $user->uid;
        $request->auth = $user;
        //角色权限验证
        $record = RoleService::permissionVerify($request);
        $response = $next($request);
        //操作日志
        if($record) {
            LoggerService::operRecord($record, $response->getCode(), $response->getContent());
        }
        return $response;
    }
}
